type ORG_RESOURCE = {
  id: string
  displayName: string
  enDisplayName: string
  resourceUrl: string
  resourceIcon: string
  parentId: string
  displayType: string
  iframeUrl: string
  [key: string]: any,
}

type Menu = {
  id: string
  label: string
  enLabel: string
  icon: string
  pid: string
  url: string
  children?: Menu[]
}

export function useResource( resources: ORG_RESOURCE[], all: boolean = false ) {
  let map: { [key: string]: Menu } = {}, menus: Menu[] = []

  // 排序所有
  resources.sort( function (a, b) {
    return (a.resourceOrder || 0) - (b.resourceOrder || 0)
  })

  // 树转成map
  function list2map() {
    resources.forEach( it => {
      map[ it.id ] = itemToMenu(it)
    } )
  }

  list2map()

  // 将原始元素转为目标元素
  function itemToMenu( it: ORG_RESOURCE ) {
    let obj: Menu = {
      id: it.id,
      label: it.displayName,
      enLabel: it.enDisplayName,
      url: it.resourceUrl,
      icon: it.resourceIcon,
      pid: it.parentId,
    }

    if( it.children ) obj.children = it.children

    return obj
  }

  // 生成树形菜单
  function list2tree() {
    resources.forEach( it => {
      const pid = map[ it.parentId ]?.id

      if( !pid ) {
        menus.push( itemToMenu( it ) )
      } else {
        map[pid].children = map[pid].children || []
        map[pid].children.push( map[it.id] )
      }
    } )
  }

  list2tree()

  return all ? map : map[menus[0].id]

}
